package cn.edu.hyit.zhao.utils;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 
 * 使用静态对象保存Spring ApplicationContent,可以在任何地方任何时间取出ApplicationContent
 * 
 * @author Neko
 * @version1.0.0
 */
public class SpringContentHolder implements ApplicationContextAware,
		DisposableBean {
	private static ApplicationContext applicationContext;
	private static Logger logger = Logger.getLogger(SpringContentHolder.class);

	/**
	 * 实现ApplicationContentAware接口，将ApplicationContent注入到静态变量中
	 */
	@Override
	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {
		logger.debug("已经缓存了Spring的上下文对象");
		applicationContext = arg0;

	}

	/**
	 * 取得ApplicationContent
	 * 
	 * @return
	 */
	public static ApplicationContext getApplicationContent() {
		return applicationContext;
	}

	/**
	 * 实现DisposableBean接口, 在Context关闭时清理静态变量
	 */
	@Override
	public void destroy() throws Exception {
		SpringContentHolder.claerHolder();
	}

	/**
	 * 从静态变量ApplicationContent中获取Bean，并自动转型为请求的类型
	 * 
	 * @param requiredType
	 * @return
	 */
	public static <T> T getBean(Class<T> requiredType) {
		return applicationContext.getBean(requiredType);
	}

	/**
	 * 清除SpringContextHolder中的ApplicationContext为Null
	 */
	public static void claerHolder() {
		if (logger.isDebugEnabled()) {
			logger.debug("清除SpringContextHolder中的ApplicationContext:"
					+ applicationContext);
		}
		applicationContext = null;
	}

}
